package com.xjx.common.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;

import com.xjx.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.xjx.common.enums.BizCodeEnum.SYSTEM_ERROR;


/**
 * * @Author xujunxia
 * * @Date 2024-12-12 17:31
 * * @Description TODO
 * * wb-0455@dtdream.com
 **/
@Slf4j
public class DocUtil {


    public static List<String> getFileNames(String directory) throws IOException {
        List<InputStream> inputStreams = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 获取指定目录下的所有资源 URL
        Enumeration<URL> resources = classLoader.getResources(directory);
        List<String> fileNames = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            File dir = new File(URLDecoder.decode(resource.getFile(), "utf-8"));
            fileNames.add(dir.getAbsolutePath());
            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            // 构建资源路径
                            fileNames.add(file.getName());
                        }
                    }
                }
            }
        }
        return fileNames;
    }

    public static List<InputStream> getFilesAsInputStreams(String directory) throws IOException {
        List<InputStream> inputStreams = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 获取指定目录下的所有资源 URL
        Enumeration<URL> resources = classLoader.getResources(directory);

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            File dir = new File(URLDecoder.decode(resource.getFile(), "utf-8"));
            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            // 构建资源路径
                            String resourcePath = directory + "/" + file.getName();
                            InputStream inputStream = classLoader.getResourceAsStream(resourcePath);
                            if (inputStream != null) {
                                inputStreams.add(inputStream);
                            }
                        }
                    }
                }
            }
        }
        return inputStreams;
    }

//    public static List<String> getCSVHeaderFields(File file) {
//        List<String> headerFields = new ArrayList<>();
//        try (Reader reader = new FileReader(file);
//             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {
//            // 获取表头
//            String[] headers = csvParser.getHeaderNames().toArray(new String[0]);
//            for (String header : headers) {
//                headerFields.add(header);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return headerFields;
//    }



    public static boolean isGarbage(String str) {
        int garbageCount = 0;
        int validCount = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            // 这里简单判断 ASCII 可见字符和中文字符范围
            if ((c >= 32 && c <= 126) || (c >= 0x4E00 && c <= 0x9FA5)) {
                validCount++;
            } else {
                garbageCount++;
            }
        }
        // 如果乱码字符比例超过一定阈值（这里设为 30%），认为是乱码
        return (double) garbageCount / (garbageCount + validCount) > 0.4;
    }


    public static String customDetectCharset(File file) {
        List<Charset> charsetList = Stream.of(
                        Charset.forName("UTF-8"),
                        Charset.forName("UTF-16"),
                        Charset.forName("GBK"),
                        Charset.forName("GB2312"),
                        Charset.forName("ISO-8859-1"))
                .collect(Collectors.toList());
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] data = readAllBytes(fis);
            for (Charset charset : charsetList) {
                try {
                    String str =  new String(data, charset);
                    if(isGarbage(str)){
                        throw new BizException(SYSTEM_ERROR);
                    }
                    return charset.name();
                } catch (Exception e) {
                    // 解码失败，尝试下一个编码
                    log.error("解码失败，尝试下一个编码");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readAllBytes(FileInputStream fis) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            byte[] allBytes = bos.toByteArray();
            return allBytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




    public static String getSuffix(String minioUrl) {
        String docUrl = minioUrl;
        int lastDotIndex = docUrl.lastIndexOf(".");
        if (!docUrl.contains(".")) {
            return "";
        }
        String suffix = docUrl.substring(lastDotIndex);
        return suffix;
    }

    public static final Set<String> IMAGE_SUFFIXES = Stream.of(  "jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "ico").collect(Collectors.toSet());


    public static boolean isImage(String filename) {
        // 处理空值或无效文件名
        if (filename == null || filename.trim().isEmpty()) {
            return false;
        }

        // 提取后缀（从最后一个 . 之后开始截取，忽略扩展名前的点）
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex == -1 || dotIndex == filename.length() - 1) { // 无后缀或后缀为空（如 "file."）
            return false;
        }
        String suffix = filename.substring(dotIndex + 1).toLowerCase(); // 转换为小写

        // 检查是否在合法图片后缀列表中
        return IMAGE_SUFFIXES.contains(suffix);
    }







    private static String convertElementToString(org.w3c.dom.Element element) throws Exception {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        return writer.writeToString(element);
    }



    public static boolean containsChinese(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isChinese(char c) {
        return c >= '\u4e00' && c <= '\u9fff';
    }


}
